﻿@using System.ComponentModel.DataAnnotations
@using Masa.Blazor.Components.Form
@inject IPopupService PopupService
@inject IJSRuntime JSRuntime

<MCard Width="360" Outlined Class="pa-4 mx-auto">
    <MForm Model="_model"
           OnSubmit="@HandleOnInvalidSubmit">
        <MTextField @bind-Value="_model.Name"
                    Id="model-name"
                    Counter="10"
                    Filled
                    Label="Name">
        </MTextField>
        <MTextField @bind-Value="_model.Email"
                    Filled
                    Label="E-mail">
        </MTextField>
        <MButton Type="submit" Block Color="primary">Submit</MButton>

    </MForm>
</MCard>

@code {

    class Model
    {
        [Required] [MaxLength(10, ErrorMessage = "Name must be less than 10 characters")]
        public string? Name { get; set; }

        [Required] [EmailAddress] public string? Email { get; set; }
    }

    private Model _model = new();

    private void HandleOnInvalidSubmit(SubmitEventArgs args)
    {
        if (args.Valid)
        {
            return;
        }

        var firstResult = args.Results.FirstOrDefault();
        if (firstResult != null)
        {
            _ = PopupService.EnqueueSnackbarAsync($"Field '{firstResult.Field}' got an error", firstResult.ErrorMessages.FirstOrDefault());
            _ = JSRuntime.InvokeVoidAsync(JsInteropConstants.Focus, "#" + firstResult.Id);
        }
    }

}